

class SocketConnect 
{
    constructor() 
    {
        
    }

    close() 
    {
        this.stopBeat()

        if (this.mClient) 
        {
            this.mClient.destroy()

            this.mClient = null
        }
    }

    connect(url, onOpen, onClose, onError, onMessage) 
    {
        let address = url

        if (cc.sys.isNative)
        {
            //address = address.replace('wss', 'ws')
        }

        let WebSocketClient = require('WebSocketClient')
        
        this.mClient = new WebSocketClient(this)

        this.mClient.connect(address, 
            (reconnect) => 
            {
                onOpen(this, reconnect)
            }, 

            onMessage, 
            
            () =>
            {
                this.stopBeat()
                onClose(this)
            }, 
            () =>
            {
                this.stopBeat()
    
                onError(this)
            }
        )
    }

    reconnect(callback)
    {
        if (this.mClient)
        {
            this.mClient.reconnect(callback)
        }
        else
        {
            callback && callback(false)
        }
    }

    send(data) 
    {
        if (this.mClient) 
        {
            return this.mClient.send(data)
        }

        return false
    }

    startBeat(data, delta, lostCountNum, lostCallback) 
    { 
        this.stopBeat()
        
        let count = 0, sendTime = 0

        let requestBeat = () =>{

                if (count > lostCountNum && lostCountNum > 0) 
                {
                    Log.e("SocketConnect", "heart beat lost.")

                    lostCallback && lostCallback(this)
                } 
                else 
                {
                    ++count

                    sendTime = cc.sys.now()

                    this.send(data)
                }
            }

        this.mScheduler = setInterval(requestBeat, delta)

        requestBeat()

        let floor = Math.floor

        return (t) => {

            count = 0

            this.mReciveServerTime = cc.sys.now()

            this.mServerTime = t + floor((this.mReciveServerTime - sendTime) * 0.5)
        }
    }

    stopBeat() 
    {
        if (this.mScheduler) 
        {
            clearInterval(this.mScheduler)

            this.mScheduler = null

            Log.d("SocketConnect", "stop heart beat.")
        }
    }

    time() 
    {
        if (this.mServerTime && this.mReciveServerTime) 
        {
            return this.mServerTime + cc.sys.now() - this.mReciveServerTime
        }
        return cc.sys.now()
    }
}

export default SocketConnect
